package _01_helloworld;

import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

// Consumer: 消费者 处理消息
public class Consumer {
    public static void main(String[] args) throws MQClientException {

//        1. 创建生产者对象 defaultconsumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("hello-consumer");

//        2. consumer 连接NameServer
        consumer.setNamesrvAddr("127.0.0.1:9876");
//        3. 订阅消息 （topic tags）
        // String topic,
        // final String subExpression 表达式  *代表所有
        consumer.subscribe("my-topic","*");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
//        4. 消费消息 -- 通过注册监听器的方式 获取消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                // 自定义如何处理消息  msgs  context
                for (MessageExt msg : msgs) {
                    try {
                        System.out.println("消息： "+new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET));
                        System.out.println("消息ID: "+msg.getMsgId()+"消息队列ID"+msg.getQueueId());
                        System.out.println("消息de信息"+msg.getTopic()+","+msg.getTags());
                        System.out.println("====================================");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;//消息消费出错，稍后再发送
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//消息消费成功
            }
        });
        consumer.start();
//        5. 释放资源 如果只接收一次
       // consumer.shutdown();

    }
}
